package com.shanpin.shebao.admin.module.collect;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shanpin.core.utils.DecimalUtil;

@Service
public class AdDataService {

	@Autowired
	private AdDataDao adDataDao;
	
	/**
	 * 查询时间段内的新注册用户的付款数据
	 * @param regDate
	 * @param regDate2
	 * @param payDate
	 * @param payDate2
	 * @param market
	 * @param channel
	 * @return
	 */
	public Map<String, Object> queryAdData(String regDate, String regDate2, 
			String payDate, String payDate2,
			String market, String channel) {
		DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
		String regDate2p = DateTime.parse(regDate2, formatter)
				.plusDays(1).toString("yyyy-MM-dd");
		String payDate2p = DateTime.parse(payDate2, formatter)
				.plusDays(1).toString("yyyy-MM-dd");
		
		int regCount = 0, custCount = 0, regOrderCount = 0;
		if (StringUtils.isNotBlank(market)) {
			regCount = adDataDao.loadRegCount(regDate, regDate2p, market);
			custCount = adDataDao.loadCustCount(regDate, regDate2, market);
			if (regCount > 0) {
				regOrderCount = adDataDao.loadMRegOrderCount(regDate, regDate2p, 
						payDate, payDate2p, market);
			}
			
		} else if (StringUtils.isNotBlank(channel)) {
			regCount = adDataDao.loadRegCount(regDate, regDate2p);
			custCount = adDataDao.loadCustCount(regDate, regDate2);
			if (regCount > 0) {
				regOrderCount = adDataDao.loadCRegOrderCount(regDate, regDate2p, 
						payDate, payDate2p, channel);
			}
		} else {
			regCount = adDataDao.loadRegCount(regDate, regDate2p);
			custCount = adDataDao.loadCustCount(regDate, regDate2);
			if (regCount > 0) {
				regOrderCount = adDataDao.loadRegOrderCount(regDate, regDate2p, payDate, payDate2p);
			}
		}
		int regCust = regCount + custCount;
		Map<String, Object> map = new HashMap<>(8);
		map.put("regCount", regCount);
		map.put("custCount", custCount);
		map.put("regOrderCount", regOrderCount);
		map.put("regCust", regCust);
		map.put("regOrderRate", regCount == 0 ? 0 : DecimalUtil.divAndMul(regOrderCount, regCount, 100));
		map.put("orderRate2", regCust == 0 ? 0 : DecimalUtil.divAndMul(regOrderCount, regCust, 100));
		return map;
	}
}
